#coding=utf-8
#Boa:Dialog:DlgEditPro

import wx
import wx.grid
from product import *
from config import *
import DlgCategory,DlgKeyword

def create(parent):
    return DlgEditPro(parent)

[wxID_DLGEDITPRO, wxID_DLGEDITPROBTNCANCEL, wxID_DLGEDITPROBTNSAVE, 
 wxID_DLGEDITPROBTNSEARCHCATEGORY, wxID_DLGEDITPROBTNSEARCHKEYWORD, 
 wxID_DLGEDITPROBTNSWITCH, wxID_DLGEDITPROCHECKONUSE, wxID_DLGEDITPROGRIDUNIT, 
 wxID_DLGEDITPROSTATICBOX_UNIT, wxID_DLGEDITPROTBRAND, wxID_DLGEDITPROTCBRAND, 
 wxID_DLGEDITPROTCID, wxID_DLGEDITPROTCKEYWORD, wxID_DLGEDITPROTCMEMO, 
 wxID_DLGEDITPROTCNAME, wxID_DLGEDITPROTCSIMCODE, wxID_DLGEDITPROTCSPEC, 
 wxID_DLGEDITPROTCTYPE, wxID_DLGEDITPROTID, wxID_DLGEDITPROTKEYWORD, 
 wxID_DLGEDITPROTMEMO, wxID_DLGEDITPROTNAME, wxID_DLGEDITPROTSIMCODE, 
 wxID_DLGEDITPROTSPEC, wxID_DLGEDITPROTTYPE, 
] = [wx.NewId() for _init_ctrls in range(25)]

class DlgEditPro(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DLGEDITPRO, name=u'DlgEditPro',
              parent=prnt, pos=wx.Point(243, 85), size=wx.Size(846, 605),
              style=wx.DEFAULT_DIALOG_STYLE, title=u'\u5546\u54c1\u4fe1\u606f')
        self.SetClientSize(wx.Size(838, 571))
        self.SetToolTipString(u'')
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))

        self.TCName = wx.TextCtrl(id=wxID_DLGEDITPROTCNAME, name=u'TCName',
              parent=self, pos=wx.Point(160, 48), size=wx.Size(200, 22),
              style=0, value=u'')
        self.TCName.Bind(wx.EVT_TEXT, self.OnTCNameText,
              id=wxID_DLGEDITPROTCNAME)

        self.TName = wx.StaticText(id=wxID_DLGEDITPROTNAME,
              label=u'\u540d\u79f0\uff1a', name=u'TName', parent=self,
              pos=wx.Point(88, 48), size=wx.Size(56, 14), style=0)
        self.TName.SetAutoLayout(False)

        self.TID = wx.StaticText(id=wxID_DLGEDITPROTID,
              label=u'\u7f16\u53f7\uff1a', name=u'TID', parent=self,
              pos=wx.Point(400, 48), size=wx.Size(56, 14), style=0)
        self.TID.SetAutoLayout(False)

        self.TCID = wx.TextCtrl(id=wxID_DLGEDITPROTCID, name=u'TCID',
              parent=self, pos=wx.Point(504, 40), size=wx.Size(112, 22),
              style=0, value=u'')
        self.TCID.SetEditable(False)
        self.TCID.Enable(False)

        self.TSimCode = wx.StaticText(id=wxID_DLGEDITPROTSIMCODE,
              label=u'\u7b80\u7801\uff1a', name=u'TSimCode', parent=self,
              pos=wx.Point(88, 96), size=wx.Size(56, 14), style=0)

        self.TCSimCode = wx.TextCtrl(id=wxID_DLGEDITPROTCSIMCODE,
              name=u'TCSimCode', parent=self, pos=wx.Point(160, 88),
              size=wx.Size(200, 22), style=0, value=u'')

        self.CheckOnUse = wx.CheckBox(id=wxID_DLGEDITPROCHECKONUSE,
              label=u'\u542f\u7528', name=u'CheckOnUse', parent=self,
              pos=wx.Point(680, 48), size=wx.Size(79, 14), style=0)
        self.CheckOnUse.SetValue(True)
        self.CheckOnUse.Enable(True)

        self.TBrand = wx.StaticText(id=wxID_DLGEDITPROTBRAND,
              label=u'\u54c1\u724c\uff1a', name=u'TBrand', parent=self,
              pos=wx.Point(400, 88), size=wx.Size(51, 16), style=0)
        self.TBrand.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))

        self.TCBrand = wx.TextCtrl(id=wxID_DLGEDITPROTCBRAND, name=u'TCBrand',
              parent=self, pos=wx.Point(504, 88), size=wx.Size(112, 22),
              style=0, value=u'')

        self.TCSpec = wx.TextCtrl(id=wxID_DLGEDITPROTCSPEC, name=u'TCSpec',
              parent=self, pos=wx.Point(160, 128), size=wx.Size(416, 22),
              style=0, value=u'')

        self.TSpec = wx.StaticText(id=wxID_DLGEDITPROTSPEC,
              label=u'\u89c4\u683c\uff1a', name=u'TSpec', parent=self,
              pos=wx.Point(88, 136), size=wx.Size(64, 14), style=0)

        self.TCType = wx.TextCtrl(id=wxID_DLGEDITPROTCTYPE, name=u'TCType',
              parent=self, pos=wx.Point(160, 168), size=wx.Size(128, 22),
              style=0, value=u'')
        self.TCType.SetEditable(False)

        self.TType = wx.StaticText(id=wxID_DLGEDITPROTTYPE,
              label=u'\u7c7b\u578b\uff1a', name=u'TType', parent=self,
              pos=wx.Point(88, 176), size=wx.Size(64, 14), style=0)

        self.btnSearchCategory = wx.Button(id=wxID_DLGEDITPROBTNSEARCHCATEGORY,
              label=u'+', name=u'btnSearchCategory', parent=self,
              pos=wx.Point(296, 168), size=wx.Size(25, 25), style=0)
        self.btnSearchCategory.Bind(wx.EVT_BUTTON,
              self.OnBtnSearchCategoryButton,
              id=wxID_DLGEDITPROBTNSEARCHCATEGORY)

        self.TKeyword = wx.StaticText(id=wxID_DLGEDITPROTKEYWORD,
              label=u'\u5173\u952e\u5b57\uff1a', name=u'TKeyword', parent=self,
              pos=wx.Point(88, 216), size=wx.Size(68, 16), style=0)

        self.tcKeyword = wx.TextCtrl(id=wxID_DLGEDITPROTCKEYWORD,
              name=u'tcKeyword', parent=self, pos=wx.Point(160, 208),
              size=wx.Size(416, 26), style=0, value=u'')
        self.tcKeyword.SetEditable(False)

        self.btnSearchKeyword = wx.Button(id=wxID_DLGEDITPROBTNSEARCHKEYWORD,
              label=u'+', name=u'btnSearchKeyword', parent=self,
              pos=wx.Point(584, 208), size=wx.Size(25, 25), style=0)
        self.btnSearchKeyword.Bind(wx.EVT_BUTTON, self.OnBtnSearchKeywordButton,
              id=wxID_DLGEDITPROBTNSEARCHKEYWORD)

        self.gridUnit = wx.grid.Grid(id=wxID_DLGEDITPROGRIDUNIT,
              name=u'gridUnit', parent=self, pos=wx.Point(120, 272),
              size=wx.Size(520, 120), style=0)
        self.gridUnit.SetDefaultColSize(70)
        self.gridUnit.SetDefaultRowSize(25)
        self.gridUnit.SetRowLabelSize(15)
        self.gridUnit.SetColLabelSize(25)
        self.gridUnit.Bind(wx.grid.EVT_GRID_CELL_CHANGE,
              self.OnGridUnitGridCellChange)

        self.staticBox_unit = wx.StaticBox(id=wxID_DLGEDITPROSTATICBOX_UNIT,
              label=u'\u5355\u4f4d', name=u'staticBox_unit', parent=self,
              pos=wx.Point(88, 248), size=wx.Size(648, 160), style=0)

        self.btnSave = wx.Button(id=wxID_DLGEDITPROBTNSAVE,
              label=u'\u4fdd\u5b58', name=u'btnSave', parent=self,
              pos=wx.Point(416, 504), size=wx.Size(75, 26), style=0)
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnBtnSaveButton,
              id=wxID_DLGEDITPROBTNSAVE)

        self.btnCancel = wx.Button(id=wxID_DLGEDITPROBTNCANCEL,
              label=u'\u53d6\u6d88', name=u'btnCancel', parent=self,
              pos=wx.Point(560, 504), size=wx.Size(75, 26), style=0)
        self.btnCancel.Bind(wx.EVT_BUTTON, self.OnBtnCancelButton,
              id=wxID_DLGEDITPROBTNCANCEL)

        self.TCMemo = wx.TextCtrl(id=wxID_DLGEDITPROTCMEMO, name=u'TCMemo',
              parent=self, pos=wx.Point(192, 432), size=wx.Size(552, 48),
              style=wx.HSCROLL | wx.TE_MULTILINE, value=u'')

        self.TMemo = wx.StaticText(id=wxID_DLGEDITPROTMEMO,
              label=u'\u4ea7\u54c1\u5907\u6ce8\uff1a', name=u'TMemo',
              parent=self, pos=wx.Point(96, 432), size=wx.Size(96, 14),
              style=0)

        self.btnSwitch = wx.Button(id=wxID_DLGEDITPROBTNSWITCH,
              label=u'\u5207\u6362\u5230\u7b80\u6d01\u6a21\u5f0f',
              name=u'btnSwitch', parent=self, pos=wx.Point(96, 504),
              size=wx.Size(144, 26), style=0)
        self.btnSwitch.Bind(wx.EVT_BUTTON, self.OnBtnSwitchButton,
              id=wxID_DLGEDITPROBTNSWITCH)

    def __init__(self, parent):
        self._init_ctrls(parent)

        self.myInit()
        
    def myInit(self):
        self.STATE_ADD = 0
        self.STATE_COPY = 1
        self.STATE_MODIFY = 2
        
        #默认为新增模式
        self.state = self.STATE_ADD
        self.curProduct = None
        
        #单位表格
        title_unit = [u'单位', u'关系', u'在手数量', u'预设成本', u'预设售价',
                        u'最近进价', u'最低进价', u'最高进价']
                        
        self.gridUnit.CreateGrid(3, len(title_unit))
        for i in range(len(title_unit)):
            self.gridUnit.SetColLabelValue(i, title_unit[i])
        self.gridUnit.SetSize(self.gridUnit.GetBestSize())    

        self.TCID.SetValue(str(CDataProduct.newId()))
        
        self.curCategory = None
        self.curKeywords = []
        
    def getKeywordsStr(self):
        str = ''
        for obj in self.curKeywords:
            str += '%s  ' %obj.getFieldVal(index=CDataKeyword.COL_NAME)
        return str
    
    def getProObj(self):
        return self.curProduct
    
    def setData(self, proObj, createNew=False):
        self.curProduct = proObj
        
        proId = self.curProduct.getFieldVal(index=CDataProduct.COL_ID)
        if not (createNew):
            self.TCID.SetValue(str(proId))
            self.TCID.SetModified(False)
            self.state = self.STATE_MODIFY
        else:
            self.state = self.STATE_COPY
                
        self.TCName.SetValue(self.curProduct.getFieldVal(index=CDataProduct.COL_NAME))
        self.TCSimCode.SetValue(self.curProduct.getFieldVal(index=CDataProduct.COL_BRIEFCODE))
        self.TCSpec.SetValue(self.curProduct.getFieldVal(index=CDataProduct.COL_SPEC))
        self.TCBrand.SetValue(self.curProduct.getFieldVal(index=CDataProduct.COL_BRAND))
        self.CheckOnUse.SetValue(self.curProduct.getFieldVal(index=CDataProduct.COL_ONUSE))
        self.TCMemo.SetValue(self.curProduct.getFieldVal(index=CDataProduct.COL_MEMO))

        #分类
        categoryId = self.curProduct.getFieldVal(index=CDataProduct.COL_CATEGORYID)
        if (categoryId is not None):
            self.curCategory = CDataCategory.getFirstInstance({CDataCategory.COL_ID:categoryId})
            self.TCType.SetValue(self.curCategory.getFieldVal(index=CDataCategory.COL_NAME))
            
        #单位信息
        for row in range(CDataProduct.UNIT_CNT):
            unitIndex = CDataProduct.COL_UNIT1 + row * CDataProduct.UNIT_FIELD_CNT
            unit = self.curProduct.getFieldVal(index=unitIndex)
            if (unit is None):
                break
            
            for col in range(CDataProduct.UNIT_FIELD_CNT):
                val = self.curProduct.getFieldVal(index = unitIndex + col)
                if (val is not None):
                    import kit
                    self.gridUnit.SetCellValue(row, col, kit.myStr(val))
        
        #关键字
        self.curKeywords = CDataProLabel.getKeywordObjList(proId)
        self.tcKeyword.SetValue(self.getKeywordsStr())
        
    def saveProToDB(self):
        '''保存产品信息到数据库'''
        #Save the basic Info
        mPro = CDataProduct.factory(False) #从界面取得了id
        fields = {}
        
        proId = int(self.TCID.GetValue())
        name = self.TCName.GetValue()
        spec = self.TCSpec.GetValue()
        if (name == '' or spec == ''):
            if (name == '' and spec == ''):
                dlg = wx.MessageDialog(self,
                            u'没有填写商品名称和规格信息，二者必须至少填写一个',
                            u'提示', wx.OK|wx.ICON_ERROR)
                dlg.ShowModal()
                return False
            elif (name == ''):
                self.TCName.SetValue(spec)
                dlg = wx.MessageDialog(self, u'没有填写商品名称，自动补填商品规格',
                                        u'提示', wx.OK|wx.ICON_ERROR)
                dlg.ShowModal()
                return False
            elif (spec == ''):
                self.TCSpec.SetValue(name)
                dlg = wx.MessageDialog(self, u'没有填写商品规格，自动补填商品名称',
                                        u'提示', wx.OK|wx.ICON_ERROR)
                dlg.ShowModal()
                return False
        briefCode = self.TCSimCode.GetValue()
        
        if (self.curCategory is None):
            typeid = CDataCategory.getDefCategoryId()
        else:
            typeid = self.curCategory.getFieldVal(index=CDataCategory.COL_ID)
            
        brand = self.TCBrand.GetValue()
        onUse = int(self.CheckOnUse.GetValue())
        memo = self.TCMemo.GetValue()
        
        fields[CDataProduct.COL_ID] = proId
        fields[CDataProduct.COL_NAME] = name
        fields[CDataProduct.COL_SPEC] = spec
        fields[CDataProduct.COL_BRIEFCODE] = briefCode
        fields[CDataProduct.COL_CATEGORYID] = typeid
        fields[CDataProduct.COL_BRAND] = brand
        fields[CDataProduct.COL_ONUSE] = onUse
        fields[CDataProduct.COL_MEMO] = memo
        mPro.setMulFieldVal(fields)    

        #设置单位信息
        unitVal = []
        bBlank = False
        for i in range(self.gridUnit.GetNumberRows()):              
            for j in range(self.gridUnit.GetNumberCols()):
                val = self.gridUnit.GetCellValue(i, j)
                if (val == ''):
                    if(j == 0):# None Unit
                        bBlank = True
                    else:
                        val = None
                if (bBlank and val != '' and val is not None):
                    log(DBG, 'i=%d j=%d val=%s', (i,j,val))
                    msg = u'单位设置：第%d行缺失单位名称，请检查输入' %(i+1)
                    dlg = wx.MessageDialog(self, msg,
                                        u'提示', wx.OK|wx.ICON_ERROR)
                    dlg.ShowModal()
                    return False
                unitVal.append(val)
                
        if (unitVal[0] == ''):
            dlg = wx.MessageDialog(self, u'单位设置：第1行缺失单位名称，请检查输入',
                                        u'提示', wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return False
        
        mPro.setUnitData(unitVal)

        if(self.state == self.STATE_MODIFY and self.curProduct is not None):
            mPro.update()
        else:
            mPro.insert()
        self.curProduct = mPro

        
        #self.refreshViewProductList()
        
        #Set Keyword
        CDataProLabel.delData({CDataProLabel.COL_PROID:proId})
        for i in range(len(self.curKeywords)):
            obj = CDataProLabel.factory()
            fields = {CDataProLabel.COL_PROID:proId,
                        CDataProLabel.COL_LABELID:self.curKeywords[i].getFieldVal(index=CDataKeyword.COL_ID)}
            obj.setMulFieldVal(fields)
            obj.insert()
        
        self.curProduct = mPro
        return True
           
    def OnBtnSearchCategoryButton(self, event):
        dlg = DlgCategory.create(self)
        if (self.curCategory is not None):
            dlg.setSelection(self.curCategory)
        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x-dlgSize[0]/2, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return
        
        self.curCategory = dlg.categorySel
        if (self.curCategory is None):
            self.TCType.SetValue('')
        else:
            self.TCType.SetValue(self.curCategory.getFieldVal(index=CDataCategory.COL_NAME))

    def OnBtnSearchKeywordButton(self, event):
        dlg = DlgKeyword.create(self)
        btn = event.GetEventObject()
        btnPos = btn.ClientToScreen( (0,0) )
        btnSize =  btn.GetSize()
        dlgSize = dlg.GetSize()
        dlg.Move((btnPos.x-dlgSize[0]/2, btnPos.y+btnSize[1]))
        if (dlg.ShowModal() == wx.ID_CANCEL):
            return

        self.curKeywords = dlg.keywordSel
        self.tcKeyword.SetValue(self.getKeywordsStr())

    def OnBtnSaveButton(self, event):
        if(self.saveProToDB()):
            #产品信息发生变化，刷新缓存的信息
            #关系型数据表不用刷新，因为数据取用都是通过即时从数据库中获取
            CDataProduct.refreshDataList()
            self.EndModal(wx.ID_OK)

    def OnBtnCancelButton(self, event):
        self.EndModal(wx.ID_CANCEL)

    def OnTCNameText(self, event):
        name = self.TCName.GetValue()
        code = CBriefCode.getBriefCode(name)
        self.TCSimCode.SetValue(code)

    def OnGridUnitGridCellChange(self, event):
        '''设置单位名称时，自动把价格设置为0'''
        print 'OnGridUnitGridCellChange'
        if (event.GetCol() != 0):
            return
        
        row = event.GetRow()
        for col in range(2,8):     
            if (self.gridUnit.GetCellValue(row, col) == ''):
                self.gridUnit.SetCellValue(row, col, '0.0')

    def OnBtnSwitchButton(self, event):
        import DlgQuickAddProduct
        self.EndModal(wx.ID_CANCEL)
        
        dlg = DlgQuickAddProduct.create(self.GetParent())
        dlg.ShowModal()
        
        
        
